import 'package:flutter/material.dart';

class SliverPage extends StatefulWidget {
  const SliverPage({super.key});

  @override
  State<SliverPage> createState() => _SliverPageState();
}

class ItemData {
  final String groupName;
  final List<String> users;

  ItemData({required this.groupName, required this.users});

  static List<ItemData> get testData => [
        ItemData(groupName: '幻将术士', users: ['梦小琴', '梦千']),
        ItemData(groupName: '幻将剑客', users: ['杰特', '龙少', '莫西', '克劳斯', '马尔斯', '梦爵士']),
        ItemData(groupName: '幻将法师', users: ['梦小琴', '梦千', '梦爵士']),
        ItemData(groupName: '幻将牧师', users: ['梦小琴', '梦千', '梦爵士', '梦小琴', '梦千', '梦爵士', '梦小琴', '梦千', '梦爵士', '梦小琴', '梦千', '梦爵士']),
        ItemData(groupName: '其他', users: List.generate(20, (index) => '小兵$index'))
      ];
}

class _SliverPageState extends State<SliverPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SliverMainAxisGroup')),
      body: CustomScrollView(
        slivers: ItemData.testData.map(_buildGroup).toList(),
      ),
    );
  }

  Widget _buildGroup(ItemData itemData) {
    return SliverMainAxisGroup(slivers: [
      SliverPersistentHeader(
        pinned: true,
        delegate: HeaderDelegate(itemData.groupName),
      ),
      SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) => _buildItemByUser(itemData.users[index]),
          childCount: itemData.users.length,
        ),
      ),
    ]);
  }

  Widget _buildItemByUser(String user) {
    return Container(
      alignment: Alignment.center,
      height: 56,
      child: Row(
        children: [
          const Padding(
            padding: EdgeInsets.only(left: 20, right: 10),
            child: FlutterLogo(size: 30),
          ),
          Text(
            user,
            style: const TextStyle(fontSize: 16),
          )
        ],
      ),
    );
  }
}

class HeaderDelegate extends SliverPersistentHeaderDelegate {
  const HeaderDelegate(this.title);

  final String title;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(alignment: Alignment.centerLeft, color: const Color(0xffF6F6F6), padding: const EdgeInsets.only(left: 20), height: 40, child: Text(title));
  }

  @override
  double get maxExtent => minExtent;

  @override
  double get minExtent => 40;

  @override
  bool shouldRebuild(covariant HeaderDelegate oldDelegate) => title != oldDelegate.title;
}
